package main

import (
	"bufio"
	"code.google.com/p/bouncer"
	"flag"
	"fmt"
	"os"
)

var bounceRoot = flag.String("base", "http://natulte.net:4242/bounce/",
	"Bouncer server base URL")

func main() {
	flag.Parse()
	if len(flag.Args()) != 1 {
		fmt.Println("Usage:", os.Args[0], "<key>")
		return
	}

	key := flag.Args()[0]
	fmt.Println("Bouncing with key", key)
	url := fmt.Sprintf("%s%s", *bounceRoot, key)
	conn, _, err := bouncer.Dial(url)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Connection established")
	fmt.Println("You now have a dumb chat session. Good luck.")

	die := make(chan bool, 2)
	defer conn.Close()

	go func() {
		buf := bufio.NewReader(conn)
		for {
			line, _, err := buf.ReadLine()
			if err != nil {
				fmt.Println("conn reader:", err)
				die <- true
				return
			}
			fmt.Println(string(line))
		}
	}()
	go func() {
		buf := bufio.NewReader(os.Stdin)
		for {
			line, _, err := buf.ReadLine()
			if err != nil {
				fmt.Println("stdin reader:", err)
				die <- true
				return
			}
			conn.Write(line)
			conn.Write([]byte("\n"))
		}
	}()
	<-die
	return
}
